/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.user.service;

import com.hyts.infodb.enums.SystemConfiguration;
import com.hyts.infodb.user.bean.bo.UserBO;
import com.hyts.infodb.user.bean.dto.LoginParamDTO;
import com.hyts.infodb.user.bean.dto.LoginResultDTO;
import com.hyts.infodb.user.bean.dto.UserDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.io.Serializable;

/**
 * @author LiBo/Alex
 * @version V1.0 
 */
public interface LoginService {
    
    /**  
     * @param dto
     * @return
     * @exception
     */ 
     LoginResultDTO login(LoginParamDTO dto);
    
    /**  
     * @param dto
     * @return
     * @exception
     */ 
     LoginResultDTO logout(LoginParamDTO dto);

    /**
     * 添加用户登录日志
     * @return
     */
    boolean changeLoginLogData(Serializable id);

    /**
     * 私有的方法进行控制登录操作
     * @param user
     * @return
     */
    default UserDTO login(UserBO user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(user.getUserName());
        token.setPassword(user.getPassword().toCharArray());
        UserDTO userDTO = new UserDTO();
        try {
            subject.login(token);
            userDTO.setCode(SystemConfiguration.ResultConfiguration.SUCCESS.getCode());
            subject.getSession(true).setAttribute(SystemConfiguration.DEFAULT_USER_CODE,user.getUserName());
        } catch (Exception e) {
            userDTO.setCode(SystemConfiguration.ResultConfiguration.FAILURE.getCode());
            if(e instanceof IncorrectCredentialsException) {
                userDTO.setMessage("用户名或者密码错误!");
            }else {
                userDTO.setMessage(e.getMessage());
            }
        }
        return userDTO;
    }
}
